package com.umeox.watch.moto.launcher;


import static com.umeox.moto.common.log.Logger.getTime;
import static com.umeox.moto.watch.themes.AppJob.EXTRA_JOB_TYPE;
import static com.umeox.moto.watch.themes.AppJob.JOB_TYPE_SKIN_LOAD;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.tencent.bugly.crashreport.CrashReport;
import com.umeox.moto.common.utils.AndroidUtils;
import com.umeox.moto.common.utils.AppUtils;
import com.umeox.moto.watch.themes.skin.loader.ResourceManager;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.launcher.constant.Constant;
import com.umeox.watch.moto.launcher.keyboard.SoftKeyboardService;
import com.umeox.watch.moto.launcher.service.AppJobService;
import com.umeox.watch.moto.pedometer.base.BaseApp;
import com.umeox.watch.moto.pedometer.util.CacheImpl;
import com.umeox.watch.moto.pedometer.util.ICache;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;


/**
 * Created by zl on 2018/4/25.
 */

public class BaseApplication extends BaseApp {

    private static BaseApplication instance;
    private long mTime;

    public static BaseApplication getInstance() {
        if (instance == null) {
            return new BaseApplication();
        }
        return instance;
    }

    private static Context context;

    public static Context getContext() {
        return context;
    }

    @SuppressLint("WrongConstant")
    public int getBatteryLevel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager = (BatteryManager) getSystemService(Context.BATTERY_SERVICE);
            return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            return intent != null ? intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : 0;
        }
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: " + this);
        setupPhoneStateService();
        ResourceManager.getInstance().init(this);
        final Intent service = new Intent(this, AppJobService.class);
        service.putExtra(EXTRA_JOB_TYPE, JOB_TYPE_SKIN_LOAD);
        startService(service);
        super.onCreate();
        //Bugly start
        CrashReport.UserStrategy userStrategy = new CrashReport.UserStrategy(this);
        userStrategy.setAppChannel(BuildConfig.FLAVOR + "-" + AndroidUtils.getDeviceId());
        CrashReport.initCrashReport(this, "a018aa68d5", false, userStrategy);
        //Bugly end

        mTime = getTime(0);
        CacheImpl.getInstance().put(ICache.KEY_DEVICE_DATA, false);
        CacheImpl.getInstance().put(ICache.KEY_BOOT, 1);
        context = getApplicationContext();
        instance = this;
        DataProvider.initialize(this);
        AppUtils.initialize(this);
        getContentResolver().registerContentObserver(DataProvider.DeviceCodeProvider.getUri(), true, mContentObserver);
        TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        mTelephonyManager.listen(new CallStateListener(), PhoneStateListener.LISTEN_CALL_STATE);


        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                .setDefaultFontPath("fonts/Roboto-Medium.ttf")
                .setFontAttrId(R.attr.fontPath)
                .build()
        );
    }

    private void startSoftKeyboardService() {
        Intent intent = new Intent(this, SoftKeyboardService.class);
        startService(intent);
    }


    public static Uri getUriFromDrawableRes(Context context, int id) {
        Resources resources = context.getResources();
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + resources.getResourcePackageName(id) + "/"
                + resources.getResourceTypeName(id) + "/"
                + resources.getResourceEntryName(id);
        return Uri.parse(path);
    }

    private static final String TAG = Constant.TAG_LAUNCHER;
    private ContentObserver mContentObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            String qrCode = DataProvider.getQrCode();

            Log.d(TAG, "Launcher onChange qrCode:" + qrCode);
            if (TextUtils.isEmpty(qrCode)) {
                return;
            }
            CacheImpl.getInstance().put(ICache.KEY_DEVICE_DATA, true);
            getContentResolver().unregisterContentObserver(mContentObserver);
        }

    };


    @Override
    public void onTerminate() {
        super.onTerminate();
    }


    public void setupPhoneStateService() {
        Intent intent = new Intent();
        intent.setAction("com.umeox.phone.PHONE_STATE_SERVICE");
        intent.setPackage("com.umeox.phone");
        intent.putExtra("phone", "phone");
        startService(intent);
    }

    class CallStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String phoneNumber) {
            super.onCallStateChanged(state, phoneNumber);
            if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
                AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                int mCallCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
                final int callVolume = CacheImpl.getInstance().get(CacheImpl.KEY_VOLUME_VOICE_CALL, mCallCurrentVolume);
                mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, callVolume, AudioManager.USE_DEFAULT_STREAM_TYPE);
            }
        }
    }
}
